﻿using System;
using System.Collections.Generic;
using System.Text;

namespace AmuTools.Web
{
    public class UrlHelper
    {
        public string BaseUrl { get; private set; }

        public Dictionary<string, string> Querys { get; private set; }

        public string Url
        {
            get
            {
                List<string> list = new List<string>();
                foreach(var item in Querys)
                {
                    list.Add($"{item.Key}={item.Value}");
                }

                if(list.Count > 0)
                {
                    return $"{BaseUrl}?{string.Join("&", list)}";
                }
                else
                {
                    return BaseUrl;
                }
            }
        }

        public UrlHelper(string url)
        {
            if(url == null)
            {
                throw new Exception("url不能为null");
            }

            string[] arr = url.Split('?');
            BaseUrl = arr[0];

            Querys = new Dictionary<string, string>();
            if(arr.Length > 1)
            {
                Add(arr[1]);
            }
        }

        public UrlHelper Add(string query)
        {
            if (query == null) return this;

            var arr = query.Split('&');
            foreach(string item in arr)
            {
                var kv = item.Split('=');
                if(kv.Length == 2)
                {
                    Add(kv[0], kv[1]);
                }
            }

            return this;
        }

        public UrlHelper Add(string key, string value)
        {
            Querys.Add(key, value);
            return this;
        }
    }
}
